<template>
  <el-form v-loading="formLoading" :model="form" label-width="120px">
    <el-form-item label="视频 名称">
      <el-input v-model="form.courseVideoName" :disabled="readOnly"/>
    </el-form-item>
    <el-form-item label="视频 目录">
      <el-select :disabled="readOnly" v-model="form.courseCatalogId" class="m-2" placeholder="Select">
        <el-option
            v-for="catalog in catalogList"
            :key="catalog.courseCatalogId"
            :label="catalog.courseCatalogName"
            :value="catalog.courseCatalogId"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="视频 文件">
      <el-upload class="upload-demo" action="" :limit="1" :on-exceed="onExceed" :on-remove="fileRemove"
                 :on-change="fileChange" :auto-upload="false" >
        <template #trigger>
          <el-button :disabled="readOnly" type="primary">选择 视频</el-button>
        </template>

        <template #tip>
          <div class="el-upload__tip">
            请上传 mp4 格式文件 , &lt; 1000MB
          </div>
        </template>
      </el-upload>

    </el-form-item>

    <el-form-item v-if="!readOnly">
      <el-button type="primary" @click="onSubmit" v-if="createVideo">上传</el-button>
<!--      <el-button type="primary" @click="onSave" v-if="!readOnly&!createVideo">保存</el-button>-->
<!--      <el-button type="primary" v-if="readOnly&!createVideo" @click="readOnly = false">修改</el-button>-->
<!--      <el-button type="primary" v-if="!readOnly&!createVideo" @click="back">取消</el-button>-->
    </el-form-item>
  </el-form>
</template>

<script>
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";

export default {
  name: "courseVideoDetail",
  props: ['catalogList', 'createVideo'],
  setup(props) {
    const formLoading = ref(false);

    const catalogList = props.catalogList;
    const readOnly = ref(!props.createVideo);
    const form = reactive({
      courseVideoId: null,
      courseCatalogId: null,
      courseVideoUserId: null,
      courseVideoName: null,
      courseVideoPath: null,
      courseVideoLength: null,
      courseVideoSize: null,
      courseVideoCreateDate: null,
      courseVideoStatus: 1
    })

    const videoFile = null;

    return {formLoading, catalogList, readOnly, form, videoFile}
  },
  methods: {
    onSubmit() {
      //检查是否选择视频
      if (null != this.videoFile) {
        //检查是否输入名称
        if (null != this.form.courseVideoName && this.form.courseVideoName != '') {
          //检查是否选择视频所属目录
          if (null != this.form.courseCatalogId && this.form.courseCatalogId > 0) {
            //开启加载
            this.formLoading = true;
            //开始上传视频
            //将视频添加到formData中
            let w = '/api/uploadVideo';
            let formData = new FormData();
             formData.append("videoFile", this.videoFile.raw);
             formData.append("courseId",this.catalogList[0].courseId);
             formData.append("catalogId",this.form.courseCatalogId);
            let config = {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }

            axios.post(w, formData, config).then((response) => {
              if (response.data.code == 200) {
                this.form.courseVideoPath = response.data.data;
                let url = 'http://localhost:80/getFile' + response.data.data;
                this.getVideoLength(url);
                //使用定时器延长获取时间
                setTimeout(() => {
                  //检查视频长度是否为零

                  //设置视频大小
                  this.form.courseVideoSize = parseFloat(this.videoFile.size/1024/1024).toFixed(2);
                  //提交表单信息
                  axios.post('/api/creatCourseVideo',{
                    courseVideoId: this.form.courseVideoId,
                    courseCatalogId: this.form.courseCatalogId,
                    courseVideoUserId: this.form.courseVideoUserId,
                    courseVideoName: this.form.courseVideoName,
                    courseVideoPath: this.form.courseVideoPath,
                    courseVideoLength: this.form.courseVideoLength,
                    courseVideoSize: this.form.courseVideoSize,
                    courseVideoCreateDate: this.form.courseVideoCreateDate,
                    courseVideoStatus: this.form.courseVideoStatus
                  },{
                    headers:{
                      'Content-Type':'application/json;charset=UTF-8'
                    }
                  }).then((res)=>{
                    if (res.data.code == 200) {
                      ElMessage.success(res.data.msg);
                      this.readOnly = true;
                    }else{
                      ElMessage.warning(res.data.msg);
                    }
                  }).catch(function (error){
                    console.log(error)
                  })
                }, 600)

              } else {
                ElMessage.warning(response.data.msg);
              }
            }).catch(function (error) {
              console.log(error);
            }).finally(()=>{
              //关闭加载
              this.formLoading = false;
            })
          } else {
            ElMessage.warning('请选择视频目录')
          }
        } else {
          ElMessage.warning('请输入视频名称')
        }
      } else {
        ElMessage.warning('请上传视频后再尝试提交')
      }
    },
    onSave() {

    },
    back() {

    },
    onExceed() {
      //当文件超出限制时
      ElMessage.warning(
          `每次只能上传一个视频`
      )
    },
    fileChange(uploadFile) {
      //检查文件是否是mp4格式视频
      if (uploadFile.raw.type == "video/mp4") {
        //检查上传文件大小是否合格
        //存放该文件到对象中
        this.videoFile = uploadFile;
        console.log(uploadFile);
      } else {
        ElMessage.warning(
            `上传文件应为 Mp4 格式`
        )
      }

    },
    getVideoLength(url) {
      let audioElement = new Audio(url);
      let duration = 0;

      audioElement.addEventListener("loadedmetadata", function () {
        duration = audioElement.duration;
      })

      setTimeout(()=>{
        this.form.courseVideoLength = parseFloat(duration / 60).toFixed(2);
      },500)
    },
    fileRemove() {
      //当删除文件时，将本地的文件对象清空
      this.videoFile = null;
    },
  }
}
</script>

<style scoped>

</style>